package com.salton123.soulove.sailfish.video.ui.aty

import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.lxj.xpopup.XPopup
import com.salton123.soulove.api.RouterManager
import com.salton123.soulove.app.R
import com.salton123.soulove.common.Constants
import com.salton123.soulove.common.adapter.SmartRefreshDelegate
import com.salton123.soulove.sailfish.video.SailfishManager
import com.salton123.soulove.sailfish.video.ui.adapter.VideoBatchAdapter
import com.salton123.soulove.utils.Utils
import com.salton123.soulove.utils.Utils.SORT_TYPE_TIME
import com.salton123.ui.base.BaseActivity
import kotlinx.android.synthetic.main.aty_batch_operate_video.*
import kotlinx.android.synthetic.main.salton_layout_refresh_loadmore.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Time:2021/9/13 10:50 上午
 * Author:
 * Description:
 */
@Route(path = Constants.Router.Video.BATCH)
class VideoBatchActivity : BaseActivity(), SmartRefreshDelegate {
    override fun isAsyncContentView(): Boolean = false
    private val mAdapter by lazy { VideoBatchAdapter() }
    private var dirName = ""
    override fun enableTitleBar(): Boolean = false
    var toBatchOperateList = SailfishManager.toBatchOperateList
    override fun getLayoutId(): Int = R.layout.aty_batch_operate_video

    override fun initViewAndData(savedInstanceState: Bundle?) {
        dirName = intent?.getStringExtra("dirName") ?: ""
        initRefreshDelegate(recyclerView, smartRefreshLayout, mAdapter)
        refreshDataList(0)
        mAdapter.onCheckChanged = {
            if (it > 0) {
                tvDelete.text = getString(R.string.delete_count, it)
                tvDelete.setTextColor(Color.parseColor("#484848"))
                tvDelete.setBackgroundResource(R.drawable.bg_delete_btn_shape_normal)
                tvDelete.isEnabled = true
            } else {
                tvDelete.text = getString(R.string.delete)
                tvDelete.setTextColor(Color.parseColor("#c1c1c1"))
                tvDelete.setBackgroundResource(R.drawable.bg_delete_btn_shape_disable)
                tvDelete.isEnabled = false
            }

        }
        mAdapter.setOnItemChildClickListener { adapter, view, adapterPosition ->
            if (view.id == R.id.ivThumbnail) {
                SailfishManager.toPlayVideoList = mAdapter.data
                RouterManager.videoPlay(activity(), adapterPosition)
            }
        }
        tvSelectAll.setOnClickListener {
            if (tvSelectAll.text.toString() == getString(R.string.label_select_none)) {
                mAdapter.selectNone()
                tvSelectAll.text = getString(R.string.label_select_all)
            } else {
                mAdapter.selectAll()
                tvSelectAll.text = getString(R.string.label_select_none)
            }
        }

        tvDelete.setOnClickListener {
            XPopup.Builder(activity()).asConfirm(getString(R.string.batch_clear),
                getString(R.string.batch_clear_tip, mAdapter.getSelectedItems().size), {
                lifecycleScope.launch {
                    mAdapter.getSelectedItems().forEach {
                        SailfishManager.deleteVideo(it)
                        val index = mAdapter.data.indexOf(it)
                        mAdapter.data.removeAt(index)
                        mAdapter.notifyItemRemoved(index)
                    }
                }
            }, {}).show()
        }
        tvSortOrder.setOnClickListener {
            XPopup.Builder(activity())
                .isDestroyOnDismiss(true)
                .asBottomList(
                    getString(R.string.video_sort_order),
                    Utils.sortList(),
                    null,
                    -1
                ) { position, _ ->
                    lifecycleScope.launch {
                        refreshDataList(position)
                    }
                }.show()
        }

        etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                lifecycleScope.launch {
                    val ret = toBatchOperateList.filter { it.name.contains(s.toString()) }.toMutableList()
                    withContext(Dispatchers.Main) {
                        mAdapter.setNewInstance(ret)
                    }
                }
            }
        })
        tvTitleSearch.setOnClickListener {
            finish()
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            SailfishManager.toPlayVideoList = mAdapter.data
            RouterManager.videoPlay(activity(), position)
        }
    }

    private fun refreshDataList(position: Int) {
        val param = Utils.sortParam(position)
        when (param.second) {
            SORT_TYPE_TIME -> {
                if (param.first) {
                    mAdapter.setNewInstance(toBatchOperateList.sortedBy { it.createdAt }.toMutableList())
                } else {
                    mAdapter.setNewInstance(toBatchOperateList.sortedByDescending { it.createdAt }.toMutableList())
                }
            }
//            SORT_TYPE_SIZE
            else -> {
                if (param.first) {
                    mAdapter.setNewInstance(toBatchOperateList.sortedBy { it.size }.toMutableList())
                } else {
                    mAdapter.setNewInstance(toBatchOperateList.sortedByDescending { it.size }.toMutableList())
                }
            }
        }
    }

    override fun loadData(isRefresh: Boolean) {
    }
}